<template>
    <div class="user-manage">
        <el-card shadow="never" class="card-com">
            <div class="card-1">
                <searchPanel @refresh="getData('reset')">
                    <!-- 查询面板 -->
                    <template v-slot:search>
                        <el-form :inline="true" :model="listSearch" class="demo-form-inline" label-width="120px">
                            <el-row :gutter="20">
                                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                                    <el-form-item label="用户账号">
                                        <el-input v-model="listSearch.condition.username" placeholder="请输入用户账号"
                                            @keyup.enter.native="getData('search')" @clear="getData('search')"
                                            clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                                    <el-form-item label="用户姓名">
                                        <el-input v-model="listSearch.condition.nickname" placeholder="请输入用户姓名"
                                            @keyup.enter.native="getData('search')" @clear="getData('search')"
                                            clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                                    <el-form-item label="用户邮箱">
                                        <el-input v-model="listSearch.condition.email" placeholder="请输入用户邮箱"
                                            @keyup.enter.native="getData('search')" @clear="getData('search')"
                                            clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                                    <el-form-item label="手机号码">
                                        <el-input v-model="listSearch.condition.mobile" placeholder="请输入手机号"
                                            @keyup.enter.native="getData('search')" @clear="getData('search')"
                                            clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                                    <el-form-item label="用户状态">
                                        <el-select v-model="listSearch.condition.enabled" @change="getData('search')"
                                            placeholder="请选择用户状态" clearable>
                                            <el-option label="启用" value="Y" />
                                            <el-option label="禁用" value="N" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>


                            </el-row>
                            <el-row justify="end">
                                <el-button type="primary" @click="getData('search')">查询</el-button>
                                <el-button @click="getData('reset')">重置</el-button>
                            </el-row>
                        </el-form>
                    </template>
                    <!-- 字段添加 -->
                    <template v-slot:edit>
                        <el-button :icon="Plus" v-permission="'ACCOUNT:CREATE-EDIT'" type="primary"
                            @click="addEditBtn('add')" title="新增用户"></el-button>
                        <el-button :icon="listSearch.isShow ? Hide : View" @click="handleView"
                            :title="listSearch.isShow ? '隐藏敏感数据' : '查看敏感数据'"></el-button>
                        <el-dropdown :hide-on-click="false" style="margin: 0 10px;" trigger="click">
                            <el-button title="过滤表头">
                                <el-icon :size="18">
                                    <Grid />
                                </el-icon>
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-checkbox-group v-model="selectTitle" size="small" @change="checkboxChange">
                                        <el-dropdown-item v-for="item in showTitle" :key="item.prop">
                                            <el-checkbox :label="item.label" :value="item.prop" />
                                        </el-dropdown-item>
                                    </el-checkbox-group>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </searchPanel>
            </div>
            <div class="card-2">
                <OnlyTable ref="onlyTableRef" class="card-2" :tableProps="tableProp" :pageTotal="pageParams.total"
                    @get-page="handPage" :tableData="pageParams.tableData" :tableHeight="pageParams.tableHeight"
                    :loading="pageParams.loadIng">
                    <template #userEnabled="scope">
                        {{ isDisable[scope.row.enabled] }}
                    </template>
                    <template #handle="scope">

                        <el-button type="primary" size="small" link v-permission="'ACCOUNT:CREATE-EDIT'"
                            @click="addEditBtn('edit', scope.row)">编辑</el-button>
                        <template v-if="scope.row.enabled == 'Y'">
                            <el-button type="primary" v-permission="'ACCOUNT:DISABLE'" size="small" link
                                @click="bthDisableAndUse(scope.row)"> 禁用
                            </el-button>
                        </template>
                        <template v-else>
                            <el-button type="primary" v-permission="'ACCOUNT:ENABLE'" size="small" link
                                @click="bthDisableAndUse(scope.row)">启用
                            </el-button>
                        </template>

                        <el-button type="success" size="small" link @click="roleBtn(scope.row)"
                            v-permission="'ACCOUNT:ROLE'">角色分配</el-button>

                        <el-button type="danger" v-permission="'ACCOUNT:DELETE'" size="small" link
                            @click="delBtn(scope.row)">删除</el-button>
                        <el-button type="primary" size="small" link @click="detailBtn(scope.row)"
                            v-permission="'ACCOUNT:DETAIL'">详情</el-button>
                    </template>
                </OnlyTable>
            </div>
        </el-card>
        <addEdit ref="userAddEditRef" @refresh="getData('reset')" @searchEdit="getData('search')"></addEdit>
        <rolePer ref="rolePerRef" :roleList="pageParams.roleList" @refresh="getData('search')"></rolePer>
        <FormDetail :detailData="detailData" ref="detailRef"></FormDetail>
    </div>
</template>
<script setup lang='ts'>
import { reactive, onMounted, ref, defineAsyncComponent, nextTick, onUnmounted } from "vue"
import { storeToRefs } from "pinia"
import _ from "lodash"
import { Search, Plus, Hide, View } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus"
import { accountPageApiPost, accountDeleteApiDelete, accountDisableOrEnableApiPut, roleListApiPost, accountDetailApiGet, accountRelationRoleListApiPost } from "@/api/userMangement"
import useInstance from '@/hooks/useInstance';
import { userListStore } from "./pageStore"
import { menuStore } from "@/store/menu.ts"
import mittBus from '@/utils/mitt';
const { sensitive } = menuStore()

const addEdit = defineAsyncComponent(() => import("./components/addEdit.vue"))
const rolePer = defineAsyncComponent(() => import("./components/rolePer.vue"))
const detailRef = ref<{ show: (title: string, row?: any) => void }>()
defineOptions({
    name: 'userTable'
})
const { global } = useInstance();
const isDisable: any = {
    N: "禁用",
    Y: "启用"
}
const { detailData, tableProp } = storeToRefs(userListStore())
const userAddEditRef = ref<{ show: (type: string, row?: any) => void }>()
const rolePerRef = ref<{ show: (type: string, row?: any, list?: any) => void }>()
const onlyTableRef = ref()
const listSearch = reactive({
    pageNum: 1,
    pageSize: 20,
    condition: {
        username: null,
        nickname: null,
        mobile: null,
        email: null,
        enabled: null, // enabled
    },
    isShow: false,
    orders: ["created_time desc"],
});
const pageParams = reactive({
    total: 0,
    loadIng: false,
    tableData: [],
    roleList: [],
    tableHeight: 500
})
const selectTitle = ref<any>([])
const showTitle = computed(() => {
    return tableProp.value.propsList.filter(it => it.label != "操作")
})
onMounted(() => {
    selectTitle.value = tableProp.value.propsList.filter(it => it.hidden && it.label != "操作").map(item => item.prop)
    getData('search')
    getRoleList()

})

const handleView = () => {
    listSearch.isShow = !listSearch.isShow
    getData('search')
}
const showFun = (str: string) => {
    const arr = sensitive && sensitive.filter((item: any) => item.code == str)
    if (arr && arr.length) {
        return true
    }
    return false
}


const checkboxChange = (val: string[]) => {
    pageParams.loadIng = true
    // 进入的 全部为 true 没有的为false
    tableProp.value.propsList = tableProp.value.propsList.map((item: any) => {
        if (val.includes(item.prop)) {
            return {
                ...item,
                hidden: true
            }
        } else if (item.label == "操作") {
            return {
                ...item,
                hidden: true
            }
        } else {
            return {
                ...item,
                hidden: false
            }
        }
    })
    pageParams.loadIng = false
}
const getRoleList = async () => {
    const res = await roleListApiPost({
        id: null,
        code: null,
        name: null
    })
    if (res.code == 20000) {
        pageParams.roleList = res.data
    }
}
const addEditBtn = (type: string, row?: any) => {
    if (type === "add") {
        userAddEditRef.value?.show('add')
    } else {
        userAddEditRef.value?.show('edit', JSON.parse(JSON.stringify(row)))
    }
}
const getData = async (type: string) => {
    pageParams.loadIng = true
    if (type === 'reset') {
        listSearch.pageNum = 1
        listSearch.pageSize = 20
        listSearch.condition.username = null
        listSearch.condition.nickname = null
        listSearch.condition.mobile = null
        listSearch.condition.email = null
        listSearch.condition.enabled = null
        onlyTableRef.value.initPagination()
    }
    try {
        const res = await accountPageApiPost(listSearch)
        if (res.code == 20000) {
            pageParams.tableData = res.data.records
            pageParams.total = res.data.total
            pageParams.loadIng = false
        }
    } catch (error) {
        console.log("accountPageApiPost");
    } finally {
        mittBus.emit('scrollUpdate')
    }


}
const handPage = (val: { pageNum: number; pageSize: number }) => {
    listSearch.pageNum = val.pageNum;
    listSearch.pageSize = val.pageSize;
    getData("search");
};
const delBtn = async (row: any) => {
    const flag = await global.$myconfirm(`是否确定删除该数据？  ${row.username}`)
    if (flag) {
        const res = await accountDeleteApiDelete({ id: row.id })
        console.log(res.data);
        if (res.code == 20000) {
            ElMessage({
                type: "success",
                message: "数据删除成功"
            })
            getData('search')
        } else {
            ElMessage({
                type: "error",
                message: "数据删除失败"
            })
        }

    }
}
const roleBtn = async (row: any) => {
    console.log(row);
    try {
        const res = await accountRelationRoleListApiPost({ accountId: row.id })
        if (res.code == 20000) {
            const arr = res.data.map(it => it.roleCode)

            rolePerRef.value?.show('add', row, arr)
        }
    } catch (error) {
        ElMessage({
            type: "error",
            message: "数据请求失败"
        })
    }

}
const bthDisableAndUse = async (row: any) => {
    //accountDisableOrEnableApiPut // 如何判断员工的状态
    const str = row.enabled == "Y" ? "确定禁用该员工账号？" : "确定启用该员工账号"
    const flag = await global.$myconfirm(`${str}`)
    if (flag) {
        const res = await accountDisableOrEnableApiPut({ id: row.id, enabled: row.enabled == "Y" ? "N" : "Y" })
        console.log(res.data);
        if (res.code == 20000) {
            ElMessage({
                type: "success",
                message: "数据修改成功"
            })
            getData('search')
        } else {
            ElMessage({
                type: "error",
                message: "数据修改失败"
            })
        }

    }
}

const detailBtn = async (row: any) => {
    try {
        const res = await accountDetailApiGet({ id: row.id })
        if (res.code != 20000) return
        detailData.value = detailData.value.map(item => {
            if (item.prop == "isDisable") {
                return {
                    ...item,
                    value: isDisable[res.data[item.prop]]

                }
            } else {
                return {
                    ...item,
                    value: res.data[item.prop]
                }
            }
        })
        detailRef.value.dialogBasic.height = 450
        detailRef.value?.show('edit')
    } catch (error) {

    }
}
</script>
<style lang='scss' scoped>
.user-manage {
    height: calc(100vh - 70px);

    .card-com {
        display: flex;
        flex-direction: column;
        // height: 100%;

        .card-2 {
            flex-grow: 1;
        }
    }
}
</style>
